package com.hdg.boot.excel_listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.hdg.boot.bo.XirMdBo;
import com.hdg.boot.dto.ExcelAddDownloadDto;
import com.hdg.boot.dto.ExcelUpdateDownloadDto;
import com.hdg.boot.mapper.NewAddTableMapper;
import com.hdg.boot.mapper.NewUpdateTableMapper;
import com.hdg.boot.mapper.XirMdMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author huangdenggong
 * @create 2022-11-05 19:49
 * describeu
 */
@Service
public class UploadListener implements ReadListener<XirMdBo> {
    public UploadListener() {

    }

    private static final Logger logger = LoggerFactory.getLogger(UploadListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<XirMdBo> saveList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private String tableName;
    @Resource
    XirMdMapper xirMdMapper;



    /**
     * @param xirMdMapper
     */
    public UploadListener(XirMdMapper xirMdMapper, String tableName) {
        this.xirMdMapper = xirMdMapper;
        this.tableName = tableName;
    }

    @Override
    public void invoke(XirMdBo xirMdBo, AnalysisContext analysisContext) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(xirMdBo));
        saveList.add(xirMdBo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (saveList.size() >= BATCH_COUNT && saveList.size() != 0) {
            saveData();
            // 存储完成清理 list
            saveList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", saveList.size());
        if (saveList.size() == 0){
            logger.error("存储数据为空");
            return;
        }
        xirMdMapper.addXirMdsByName(saveList, tableName);
        //xirMdMapper.addXirMds(saveList);
        logger.info("存储数据库成功！");
    }
}
